<template>
  <div class="app-container">
    <!--列表-->
    <div class="table-container flex-main">
      <div class="table-container-header">
        <table-toolbar @create="handleCreate" @refresh="handleFilter" @remove="removeRecord">
          <template slot="rightTool">
            <search v-model="listQuery.name" placeholder="请输入App名称" @search="handleFilter" />
          </template>
        </table-toolbar>
      </div>
      <el-table
        ref="multipleTable"
        :data="list"
        header-cell-class-name="table-header"
        fit
        height="100%"
        highlight-current-row
        @filter-change="handleFilterHandler"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick">
        <el-table-column type="selection" width="50" />
        <el-table-column align="center" prop="id" label="#" width="60">
          <template slot-scope="scope">{{ scope.$index+1 }}</template>
        </el-table-column>
        <el-table-column label="识别码" prop="appCode" width="140" align="center" />
        <el-table-column label="App名称" prop="name" min-width="260" show-overflow-tooltip />
        <el-table-column label="版本号" prop="appVersion" width="100" align="center" />
        <el-table-column label="版本名称" prop="appVersionName" width="160" />
        <el-table-column column-key="appType" :filters="appTypeOptions" :filter-multiple="false" label="类型" prop="appType" width="100" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.appType==0" class="color-primary">Android</span>
            <span v-else-if="scope.row.appType==1" class="color-success">IOS</span>
            <span v-else class="color-danger">Android</span>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="下载连接" prop="appUrl" width="80" align="center">
          <template slot-scope="scope">
            <button-option icon="iconQrcode" icon-type="svg" skin="primary" title="二维码" @click="handleQrcode(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="更新内容" prop="appRemark" width="100" align="center">
          <template slot-scope="scope">
            <el-popover
              placement="bottom"
              :title="'V'+scope.row.appVersionName+' 变更内容'"
              width="200"
              trigger="click">
              <div v-for="item in scope.row.appRemark.split('\n')" :key="item" style="line-height:25px">
                {{ item }}
              </div>
              <el-link slot="reference" type="primary" :underline="false">点击查看</el-link>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="gmtModified" label="修改时间" width="160">
          <template slot-scope="scope">{{ scope.row.gmtModified | formatDate }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="90">
          <template slot-scope="scope">
            <button-option icon="el-icon-top" skin="primary" title="升级" @click="handleUpgrade(scope.row)" />
            <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
            <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination_handler">
      <pagination v-show="total>1" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
    </div>
    <!--App版本管理侧边栏-->
    <side-box :show="sideBox.recordShow" :title="sideBox.title" @close="sideBox.recordShow =!sideBox.recordShow">
      <template slot="body">
        <el-form ref="dataForm" :rules="appVersionRules" :model="appVersionRecord" label-position="right" label-width="140px">
          <el-form-item label="唯一识别码:" prop="appCode">
            <el-input v-model="appVersionRecord.appCode" :disabled="true" maxlength="255" show-word-limit placeholder="请输入" />
          </el-form-item>
          <el-form-item label="名称:" prop="name">
            <el-input v-model="appVersionRecord.name" maxlength="50" :disabled="isUpgrade" show-word-limit placeholder="请输入名称" />
          </el-form-item>
          <el-form-item label="版本号:" prop="appVersion">
            <el-input-number v-model="appVersionRecord.appVersion" placeholder="请输入版本号" show-word-limit :min="1" style="width:100%" />
          </el-form-item>
          <el-form-item label="版本名称:" prop="appVersionName">
            <el-input v-model="appVersionRecord.appVersionName" maxlength="18" show-word-limit placeholder="请输入版本名称" />
          </el-form-item>
          <el-form-item v-if="appVersionRecord.appType===0" label="APK:" prop="appUrl">
            <simple-uploader v-model="appVersionRecord.appUrl" :mode="['file']" accept=".apk" :multiple="false" :catalog="constants.FILE_CATALOG_APP" />
          </el-form-item>
          <el-form-item v-else label="下载链接:" prop="appUrl">
            <el-input v-model="appVersionRecord.appUrl" maxlength="255" show-word-limit placeholder="请输入下载链接" />
          </el-form-item>
          <el-form-item label="更新说明:" prop="appRemark">
            <el-input
              v-model="appVersionRecord.appRemark"
              :rows="6"
              type="textarea"
              maxlength="1000"
              show-word-limit
              placeholder="请输入更新说明" />
          </el-form-item>
          <el-form-item label="APP类型:" prop="appType">
            <el-radio v-model="appVersionRecord.appType" :disabled="isUpgrade" :label="0">Android</el-radio>
            <el-radio v-model="appVersionRecord.appType" :disabled="isUpgrade" :label="1">IOS</el-radio>
          </el-form-item>
        </el-form>
      </template>
      <template slot="foot">
        <el-button type="primary" plain @click="sideBox.status==='create'?createData():updateData()">保存</el-button>
      </template>
    </side-box>
    <model-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="350px"
      :show-close="false"
      @close="dialogVisible=!dialogVisible">
      <div
        ref="appDownloadQrCode"
        v-loading="appDownloadQrCodeLoading"
        class="download-qrcode-container"
        element-loading-text="APP下载二维码导出中...">
        <div class="title">{{ appVersionRecord.name }}</div>
        <div id="qrCode" ref="qrCodeDiv" class="app-qrcode" />
        <div class="title">
          <span v-if="appVersionRecord.appType==0">Android</span>
          <span v-else-if="appVersionRecord.appType==1">IOS</span>
          v {{ appVersionRecord.appVersionName }}</div>
        <div class="desc" style="font-size:15px;margin: 10px 0px;">v {{ appVersionRecord.appVersionName }} 更新说明:</div>
        <div v-if="appVersionRecord.appRemark" class="desc">
          <div v-for="item in appVersionRecord.appRemark.split('\n')" :key="item" style="line-height:25px">
            {{ item }}
          </div>
        </div>
      </div>
      <template slot="footer">
        <el-button type="primary" plain @click="handleDownload">下 载</el-button>
      </template>
    </model-dialog>
  </div>
</template>
<script>
import html2canvas from 'html2canvas'
import QRCode from 'qrcodejs2'
export default {
  data() {
    return {
      appTypeOptions: [{
        value: 0,
        text: 'Android'
      }, {
        value: 1,
        text: 'IOS'
      }],
      list: null,
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        sort: '-appCode,-appVersion',
        name: ''
      },
      multipleSelectionRecords: [],
      sideBox: {
        recordShow: false,
        title: '',
        status: 'create' // 对话框状态
      },
      isUpgrade: false,
      appVersionRecord: {
        appCode: '',
        name: '',
        androidVersion: '',
        androidUrl: '',
        androidRemark: '',
        iosVersion: '',
        iosUrl: '',
        iosRemark: ''
      },
      appVersionRules: {
        appCode: [
          { required: true, message: '请输入识别码', trigger: 'blur' },
          { validator: this.commonValidate.validateEngOrNum, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        appVersion: [
          { required: true, message: '请输入版本号', trigger: 'blur' }
        ],
        appVersionName: [
          { required: true, message: '请输入版本名称', trigger: 'blur' }
        ],
        appUrl: [
          { required: true, message: '请输入下载链接', trigger: 'blur' }
        ],
        appRemark: [
          { required: true, message: '请输入更新内容', trigger: 'blur' }
        ]
      },
      dialogVisible: false,
      dialogTitle: 'APP下载二维码',
      appDownloadQrCodeLoading: false
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    async fetchData() {
      this.listLoading = true
      const response = await this.$store.dispatch('appVersionPage', this.listQuery)
      this.listLoading = false
      this.list = response.records
      this.total = response.total
    },
    /**
     * 搜索
     */
    handleFilter() {
      this.listQuery = {
        ...this.listQuery,
        page: 1

      }
      this.fetchData()
    },
    /**
     * 重置
     */
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        sort: '-appCode,-appVersion',
        name: ''

      }
      this.fetchData()
    },
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /**
     * 表格行过滤
     */
    handleFilterHandler(filters) {
      if (filters.appType) {
        this.listQuery = {
          ...this.listQuery,
          appType: filters.appType.join(',')
        }
      }
      this.handleFilter()
    },

    /* 新增*/
    handleCreate() {
      this.appVersionRecord = {
        appType: 0,
        appVersion: 1,
        appCode: this.T.randomString()
      }
      this.isUpgrade = false
      this.sideBox = {
        status: 'create',
        title: '新增App版本管理',
        recordShow: true
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          var appUrl = this.appVersionRecord.appUrl
          this.$store.dispatch('appVersionSave', { ...this.appVersionRecord, appUrl: this.appVersionRecord.appType === 0 ? appUrl.join(',') : appUrl }).then(response => {
            this.sideBox.recordShow = false
            this.msgSuccess('创建成功')
            this.handleReset()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },
    /* 编辑*/
    handleUpdate(row) {
      this.appVersionRecord = Object.assign({}, row) // copy obj
      this.appVersionRecord = {
        ...this.appVersionRecord,
        appUrl: this.appVersionRecord.appUrl.split(',')
      }
      this.sideBox = {
        status: 'update',
        title: '编辑[' + this.appVersionRecord.name + ']',
        recordShow: true
      }
      this.isUpgrade = false
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.appVersionRecord)
          var appUrl = tempData.appUrl

          this.$store.dispatch('appVersionUpdate', { ...tempData, appUrl: tempData.appType === 0 ? appUrl.join(',') : appUrl }).then(response => {
            this.sideBox.recordShow = false
            this.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },
    /**
     * 升级
     */
    handleUpgrade(row) {
      this.isUpgrade = true

      this.sideBox.status = 'create'
      this.sideBox.recordShow = true
      this.sideBox.title = '升级[' + row.name + '[' + row.appVersion + ']' + ']'
      this.appVersionRecord = Object.assign({}, row) // copy obj
      this.appVersionRecord = {
        ...this.appVersionRecord,
        id: null,
        appVersion: row.appVersion + 1,
        appVersionName: '',
        appUrl: null,
        appRemark: null
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          ids.push(v.id)
        })
        this.$confirm('此操作将永久删除记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('appVersionRemove', ids).then(response => {
            this.handleReset()
            this.msgSuccess('删除成功')
          }).catch(() => {})
        }).catch(() => {
        })
      } else {
        this.msgWarning('请选择要删除的记录')
      }
    },
    /**
     * 全选/反选
     */
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    handleQrcode(row) {
      this.$store.dispatch('appVersionGetNew', row.appCode).then((res) => {
        if (row.appVersion !== res.appVersion) {
          this.msgWarning('此版本不是最新版本，无法生成二维码')
          return
        }
        this.appDownloadQrCodeLoading = false
        this.appVersionRecord = row
        this.dialogVisible = true
        this.dialogTitle = `APP下载二维码`
        this.$nextTick(() => {
          document.getElementById('qrCode').innerHTML = ''
          console.log(this.$refs.qrCodeDiv)
          new QRCode(this.$refs.qrCodeDiv, {
            text: this.common.getUrl() + '/app/h5/download/' + this.appVersionRecord.appCode,
            width: 200,
            height: 200,
            colorDark: '#333333', // 二维码颜色
            colorLight: '#ffffff', // 二维码背景色
            correctLevel: QRCode.CorrectLevel.L// 容错率，L/M/H
          })
        })
      }).catch((err) => {
        console.log(err)
      })
    },
    handleDownload() {
      this.appDownloadQrCodeLoading = true
      html2canvas(this.$refs.appDownloadQrCode, {}).then(canvas => {
        const dataURL = canvas.toDataURL('image/png')
        if (dataURL !== '') {
          var a = document.createElement('a')
          a.download = `APP【${this.appVersionRecord.name}(v${this.appVersionRecord.appVersionName})下载二维码.jpg`
          a.href = dataURL
          a.click()
        }
        this.appDownloadQrCodeLoading = false
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .download-qrcode-container{
    text-align: center;
    padding: 20px;
    background: #4777e7;
    border-radius: 8px;
    .app-qrcode{
      width: 200px;
      height: 200px;
      margin: 0 auto;
     // border: 1px solid #fff;
      img{
        width: 100%;
        height: 100%;
        border-radius: 4px !important;
      }
    }
    .title{
      font-size: 16px;
      font-weight: bolder;
      margin-bottom: 10px;
      margin-top: 10px;
      color: #fff;
    }
    .desc{
      color: #fff;
      font-size: 14px;
      text-align: left;
    }
  }
</style>
